package com.giscloud.generator.controller;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import com.giscloud.commons.utils.StringUtils;
import com.giscloud.generator.entity.DatabaseEntity;
import com.giscloud.generator.entity.Table;
import com.giscloud.generator.service.GeneratorService;
import com.giscloud.generator.utils.PageUtils;
import com.giscloud.generator.utils.Query;
import com.giscloud.generator.utils.R;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * 代码生成器
 * 
 * @author giscloud
 */
@Controller
@RequestMapping("/sys/generator")
public class GeneratorController {
	@Autowired
	private GeneratorService generatorService;
	
	/**
	 * 列表
	 */
	@ResponseBody
	@RequestMapping("/list")
	public R list(@RequestParam Map<String, Object> params){
		if(params.get("id") == null){
			return R.ok().put("page", null);
		}
		Query query = new Query(params);
		PageUtils pageUtil = generatorService.queryList(params.get("tableName")+"",Long.parseLong(params.get("id").toString()),query.getPage(), query.getLimit());
		return R.ok().put("page", pageUtil);
	}
	@ResponseBody
	@RequestMapping("/listAll")
	public Map listAll(@RequestParam(value="databaseId[]",required = false) Integer[] databaseId){
		if(databaseId == null){
			return null;
		}
		Map params = Maps.newHashMapWithExpectedSize(1);
		params.put("ids",databaseId);
		List<DatabaseEntity> databaseEntitys = generatorService.listDatabases(params);
		String tableName = params.get("tableName") == null ? "" : params.get("tableName").toString();
		List<Table> list = generatorService.listAll(tableName,databaseEntitys);
		Map result = new HashMap();
		result.put("rows",list);
		result.put("total",databaseEntitys.size());
		return result;
	}

	@ResponseBody
	@RequestMapping("/listDatabases")
	public List<Table>  listDatabases(@RequestParam(value="databaseId",required = false) Integer[] databaseId){
		if(databaseId == null){
			return null;
		}
		Map params = Maps.newHashMapWithExpectedSize(1);
		params.put("ids",databaseId);
		List<DatabaseEntity> databaseEntitys = generatorService.listDatabases(params);
		String tableName = params.get("tableName") == null ? "" : params.get("tableName").toString();
		List<Table> list = generatorService.listAll(tableName,databaseEntitys);
		return list;
	}
	
	/**
	 * 生成代码
	 */
	@RequestMapping("/code")
	public void code(String tables,
					 Long databaseId,
					 String parentProjectName,
					 String projectName,
					 String packageName,
					 String moduleName,
					 String checkValues,
					 HttpServletResponse response) throws IOException{
		byte[] data = generatorService.generatorCode(tables.split(","),databaseId,parentProjectName,projectName,packageName,moduleName,checkValues);
		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename='"+parentProjectName+".zip'");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");

		IOUtils.write(data, response.getOutputStream());
	}
	/**
	 * 生成多个模型的代码
	 */
	@RequestMapping("/codes")
	public void codes(String tables,
					 String parentProjectName,
					 String projectName,
					 String packageName,
					 String moduleName,
					 String checkValues,
					 HttpServletResponse response) throws IOException{
		//加工tables

		byte[] data = generatorService.generatorCodes(tables.split(";"),parentProjectName,projectName,packageName,moduleName,checkValues);
		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename="+parentProjectName+".zip");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");

		IOUtils.write(data, response.getOutputStream());
	}

	/**
	 * 生成多个模型的代码
	 */
	@RequestMapping("/codess")
	public void codess(String tables,
					  String parentProjectName,
					  String projectName,
					  String packageName,
					  String moduleName,
					  String checkValues,
					  HttpServletResponse response) throws IOException{
		//加工tables
		String[] split = StringUtils.split(tables, ";");
		Multimap<String, String> multimap = ArrayListMultimap.create();

		for (String sp : split) {
			String[] dataTables = StringUtils.split(sp, ",");
			multimap.put(dataTables[0],dataTables[1]);
		}
		String res = "";
		HashSet<Object> objects = Sets.newHashSetWithExpectedSize(3);
		for(String s : multimap.keys()) {
			if(objects.add(s)){
				res +=s+","+StringUtils.join(multimap.get(s),",")+";";
			}
		}
		byte[] data = generatorService.generatorCodes(res.split(";"),parentProjectName,projectName,packageName,moduleName,checkValues);
		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename="+parentProjectName+".zip");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");

		IOUtils.write(data, response.getOutputStream());
	}
}
